/*
 * Copyright (c) Jack魏 2023 - 2023, All Rights Reserved.
 */

package cn.jack1996.yiyi.controller.sys;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.jack1996.yiyi.auth.CustomUserDetails;
import cn.jack1996.yiyi.service.sys.SysUserService;
import cn.jack1996.yiyi.util.JwtUtil;
import cn.jack1996.yiyi.util.Result;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 后台用户登录
 *
 * @author Jack魏
 * @since 2023/1/1 22:52
 */
@Tag(name = "系统用户登录接口", description = "系统用户登录接口")
@RestController
@RequestMapping("/sys")
public class SysLoginController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 登录之后并将token传给前台
     *
     * @param account  登录名
     * @param password 密码
     * @return 登录是否成功
     */
    @Operation(summary = "登录接口", description = "输入账号和密码进行登录")
    @Parameter(name = "account", description = "登录账号", required = true)
    @Parameter(name = "password", description = "密码", required = true)
    @GetMapping("/login")
    public Result<String> login(String account, String password) {
        // 神奇的时，这里会先执行认证管理authenticationManager配置的流程
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(account, password);
        Authentication authenticate = authenticationManager.authenticate(token);
        // 用户信息
        CustomUserDetails userDetails = (CustomUserDetails) authenticate.getPrincipal();
        Map<String, Object> payload = new HashMap<>();
        payload.put("userName", userDetails.getUsername());
        payload.put("userId", userDetails.getId());
        return Result.success(JwtUtil.getToken(payload));
    }
}
